// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package traffic

import (
	"slices"

	traffic_errors "apiote.xyz/p/szczanieckiej/traffic/errors"

	"fmt"
	"time"
)

func GetTimezone(stop Stop, t *Traffic, feedID string) (*time.Location, error) {
	if stop.Timezone != "" {
		return time.LoadLocation(stop.Timezone)
	}

	for _, feedInfos := range t.FeedInfos {
		feedInfo, ok := feedInfos[feedID]
		if ok {
			return time.LoadLocation(feedInfo.Timezone)
		}
	}
	return nil, fmt.Errorf("cannot find feedInfo for %s in timezone calculation", feedID)
}

func ParseDate(dateString string, feedName string, t *Traffic) (Validity, time.Time, error) {
	versionCode := Validity("")
	timezone, err := GetTimezone(Stop{}, t, feedName)
	if err != nil {
		return versionCode, time.Time{}, fmt.Errorf("while getting timezone: %w", err)
	}

	if dateString == "" {
		feedNow := time.Now().In(timezone)
		dateString = feedNow.Format(DateFormat)
	}
	date, err := time.ParseInLocation(DateFormat, dateString, timezone)
	if err != nil {
		return versionCode, date, fmt.Errorf("while parsing date: %w", err)
	}
	versions := t.Versions[feedName]
	slices.Reverse(versions)
	for _, v := range versions {
		if !v.ValidFrom.After(date) && !date.After(v.ValidTill) {
			versionCode = Validity(v.String())
		}
	}

	if versionCode == "" {
		return versionCode, date, traffic_errors.NoVersionError{
			Date: dateString,
		}
	}
	return versionCode, date, nil
}
